package com.zjpg.forum.controller;

import com.zjpg.forum.common.AppResult;
import com.zjpg.forum.common.ResultCode;
import com.zjpg.forum.config.AppConfig;
import com.zjpg.forum.model.User;
import com.zjpg.forum.services.IUserSevice;
import com.zjpg.forum.util.MD5Util;
import com.zjpg.forum.util.StringUtil;
import com.zjpg.forum.util.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @ClassName UserController
 * @Description: TODO
 * @Author: JCC
 * @CreateTime: 2023/8/11 23:41
 */
@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserSevice userSevice;

    /**
     *
     * @param username 用户名
     * @param nickname 昵称
     * @param password 密码
     * @param passwordRepeat 确认密码
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping("/reg")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        // 校验密码于确认密码是否一致
        if (!password.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        // 处理密码
        // 生成盐
        String salt = UUIDUtil.UUID_32();
        // 生成密文
        String ciphertext = MD5Util.md5Salt(password,salt);
        user.setSalt(salt);
        // 设置盐和密文
        user.setPassword(ciphertext);

        // 调用services层
        userSevice.createNormalUser(user);

        // 返回成功
        return AppResult.success("注册成功");
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password) {
        /*if (StringUtil.isEmpty(username,password)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }*/
        User user = userSevice.login(username,password);
        if (user == null) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);

        return AppResult.success("登录成功");
    }

    @ApiOperation("退出登录")
    @GetMapping("/loginout")
    public AppResult loginout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    /**
     * 根据id查询用户信息
     * @param request
     * @param id
     * @return
     */
    @ApiOperation("查询用户信息")
    @GetMapping("/info")
    public AppResult<User> selectById(HttpServletRequest request,
            @ApiParam("用户id") @RequestParam(value = "id",required = false) Long id) {
        User user = null;
        if (id == null) {
            HttpSession session = request.getSession(false);
            if (session == null) {
                return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
            }
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        } else {
            user = userSevice.selectById(id);
        }
        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }

    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender,
                                @ApiParam("邮箱") @RequestParam(value = "email",required = false) String email,
                                @ApiParam("电话号") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @ApiParam("个人简介") @RequestParam(value = "remark",required = false) String remark) {
        if (StringUtil.isAllEmpty(nickname,email,phoneNum,remark) && gender == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed("请输入要修改的内容");
        }
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null || user.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);
        // 调用service DAO
        userSevice.modifyInfo(updateUser);
        // 获取更新完的user数据
        user = userSevice.selectById(user.getId());
        // 重新设置session
        session.setAttribute(AppConfig.USER_SESSION,user);
        // 返回成功
        return AppResult.success(user);
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPwd(HttpServletRequest request,
                               HttpServletResponse response,
                               @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                               @ApiParam("新密码") @RequestParam("newPassword") @NonNull  String newPassword,
                               @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull  String passwordRepeat) {
        if (!passwordRepeat.equals(newPassword)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        if (newPassword.equals(oldPassword)) {
            log.warn(ResultCode.FAILED_TWO_PWD_IS_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_IS_SAME);
        }
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        userSevice.modifyPassward(user.getId(),oldPassword,newPassword);
        // 销毁session
        if (session != null) {
            session.invalidate();
        }
        return AppResult.success();
    }


   //  上传本地图片
    /*@ApiOperation("修改图片")
    @PostMapping("/updateAvatar")
    public AppResult uploadFile(MultipartFile image,HttpServletRequest request) {
        if (image == null) {
            return AppResult.failed("请选择图片");
        }
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //System.out.println(user);
        String fileName=image.getOriginalFilename(); //获取文件名以及后缀名
        fileName= UUID.randomUUID()+"_"+fileName;//重新生成文件名（根据具体情况生成对应文件名）
        //System.out.println(fileName);

        String path = System.getProperty("user.dir");
        String dirPath = path + "/src/main/resources/static/image/";
        //System.out.println(dirPath);

        File filePath=new File(dirPath);
        if(!filePath.exists()){
            filePath.mkdirs();
        }
        try{
            File uploadFile = new File(dirPath+fileName);
            //将文件写入磁盘
            image.transferTo(uploadFile);

            // 修改图片URL
            //System.out.println(uploadFile.getName());
            User updateUserAvatarUrl = new User();
            updateUserAvatarUrl.setAvatarUrl("image/" +uploadFile.getName());
            updateUserAvatarUrl.setId(user.getId());
            //System.out.println(updateUserAvatarUrl.getAvatarUrl());
            userSevice.modifyAvatar(updateUserAvatarUrl);
            User resultUser = userSevice.selectById(user.getId());
            //System.out.println(resultUser);
            return AppResult.success(resultUser);

        }catch (Exception e){
            return AppResult.failed();
        }
        //携带上传状态信息回调到文件上传页面
    }*/


    // 上传jar包同级文件
    @ApiOperation("修改头像")
    @PostMapping("/updateAvatar")
    public AppResult uploadFile(MultipartFile image,HttpServletRequest request) {
        if (image == null) {
            return AppResult.failed("请选择图片");
        }
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //System.out.println(user);
        String fileName=image.getOriginalFilename(); //获取文件名以及后缀名
        fileName= UUID.randomUUID()+"_"+fileName;//重新生成文件名（根据具体情况生成对应文件名）
        //System.out.println(fileName);

        //String path = System.getProperty("user.dir");
        //String dirPath = path + "/src/main/resources/static/image/";
        //System.out.println(dirPath);


        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        //在jar包所在目录下生成一个image文件夹用来存储上传的图片
        String dirPath = jarF.getParentFile().toString()+"/classes/static/image/";

        File filePath=new File(dirPath);
        if(!filePath.exists()){
            filePath.mkdirs();
        }
        try{
            File uploadFile = new File(dirPath+fileName);
            //将文件写入磁盘
            image.transferTo(uploadFile);

            // 修改图片URL
            //System.out.println(uploadFile.getName());
            User updateUserAvatarUrl = new User();
            updateUserAvatarUrl.setAvatarUrl("image/" +uploadFile.getName());
            updateUserAvatarUrl.setId(user.getId());
            //System.out.println(updateUserAvatarUrl.getAvatarUrl());
            userSevice.modifyAvatar(updateUserAvatarUrl);
            User resultUser = userSevice.selectById(user.getId());
            session.setAttribute(AppConfig.USER_SESSION,resultUser);
            //System.out.println(resultUser);
            //携带上传状态信息回调到文件上传页面
            return AppResult.success(resultUser);

        }catch (Exception e){
            return AppResult.failed();
        }
    }

    // 上传jar包下的项目的静态文件
    //@ApiOperation("修改头像")
    //@PostMapping("/updateAvatar")
    //public AppResult uploadFile(MultipartFile image,HttpServletRequest request) {
    //    if (image == null) {
    //        return AppResult.failed("请选择图片");
    //    }
    //    HttpSession session = request.getSession(false);
    //    User user = (User) session.getAttribute(AppConfig.USER_SESSION);
    //    if (user == null || user.getDeleteState() == 1) {
    //        log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
    //        return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
    //    }
    //    //System.out.println(user);
    //    String fileName=image.getOriginalFilename(); //获取文件名以及后缀名
    //    fileName= UUID.randomUUID()+"_"+fileName;//重新生成文件名（根据具体情况生成对应文件名）
    //    //System.out.println(fileName);
    //
    //    //String path = System.getProperty("user.dir");
    //    //String dirPath = path + "/src/main/resources/static/image/";
    //    //System.out.println(dirPath);
    //
    //
    //    ApplicationHome h = new ApplicationHome(getClass());
    //    File jarF = h.getSource();
    //    //在jar包所在目录下生成一个image文件夹用来存储上传的图片
    //    String dirPath = jarF.getParentFile().toString()+"/classes/static/image/";
    //
    //    File filePath=new File(dirPath);
    //    if(!filePath.exists()){
    //        filePath.mkdirs();
    //    }
    //    try{
    //        File uploadFile = new File(dirPath+fileName);
    //        //将文件写入磁盘
    //        image.transferTo(uploadFile);
    //
    //        // 修改图片URL
    //        //System.out.println(uploadFile.getName());
    //        User updateUserAvatarUrl = new User();
    //        updateUserAvatarUrl.setAvatarUrl("image/" +uploadFile.getName());
    //        updateUserAvatarUrl.setId(user.getId());
    //        //System.out.println(updateUserAvatarUrl.getAvatarUrl());
    //        userSevice.modifyAvatar(updateUserAvatarUrl);
    //        User resultUser = userSevice.selectById(user.getId());
    //        //System.out.println(resultUser);
    //        //携带上传状态信息回调到文件上传页面
    //        return AppResult.success(resultUser);
    //
    //    }catch (Exception e){
    //        return AppResult.failed();
    //    }
    //}
}
